package com.quanyan.club.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.BaseService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.common.vo.Image;
import com.quanyan.common.vo.resp.RespCity;
import com.quanyan.common.vo.resp.RespDistrict;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhuo.shi on 2016/5/30.
 */
@Service
public class BaseServiceImpl implements BaseService{

    private static final Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);

    @Autowired
    private TbClubTypeMapper clubTypeMapper;
    @Autowired
    private TbClubPropertyMapper clubPropertyMapper;
    @Autowired
    public UserServiceFacade userServiceFacade;
    @Autowired
    private TbCityMapper cityMapper;
    @Autowired
    private TbDistrictMapper districtMapper;
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Autowired
    private TbClubMapper clubMapper;

    @Value("${search.cloud.url}")
    public String searchCloudUrl;
    @Value("${message.push.service.url}")
    public String messagePushServiceUrl;

    @Override
    public Integer getCityIdByName(String cityName) {
        if (StringUtil.isBlankOrNull(cityName)){
            return -1;
        }
        if (cityName.lastIndexOf("市") != -1) {
            cityName = cityName.substring(0, cityName.lastIndexOf("市"));
        }
        TbCityExample example = new TbCityExample();
        TbCityExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(cityName);
        int count = cityMapper.countByExample(example);
        if (count == 1) {
            Integer cityId = cityMapper.selectByExample(example).get(0).getId();
            return cityId;
        }
        return -1;
    }

    @Override
    public RespCity getCity(Integer cityId) {
        TbCity city = cityMapper.selectByPrimaryKey(cityId);
        //判断是否是存在的
        if (null == city || city.getIsEnable() == Constants.IS_ENABLE_FALSE){
            return null;
        }
        RespCity respCity = new RespCity();
        respCity.setId(cityId);
        respCity.setIsActive(city.getIsActive());
        Image image = new Image();
        image.setImageUrl(city.getAttachUrl());
        respCity.setImage(image);
        if (null != city.getPinyin()) {
            respCity.setInitial(city.getPinyin().substring(0,1));//首字母
        }
        respCity.setName(city.getName());
        respCity.setPinyin(city.getPinyin());
        respCity.setLat(city.getLat());
        respCity.setLng(city.getLng());
        respCity.setDesc(city.getCityDesc());
        return respCity;
    }

    @Override
    public PageObj<List<RespCity>> getCityList(Integer provinceId, String keyWords, Integer pageNo, Integer pageSize) {
        TbCityExample example = new TbCityExample();
        TbCityExample.Criteria criteria = example.createCriteria();
        if (provinceId != null && provinceId != 0) {
            criteria.andProvinceIdEqualTo(provinceId);
        }
        if (StringUtils.isNotEmpty(keyWords)) {
            criteria.andNameLike("%" + keyWords + "%");
        }
        criteria.andIsEnableEqualTo((int)Constants.IS_ENABLE_TRUE);
        int totalNum = cityMapper.countByExample(example);
        example.setLimit(Limit.buildLimit(pageNo, pageSize));
        List<TbCity> cityList = cityMapper.selectByExample(example);
        List<RespCity> respCities = new ArrayList<>();
        if (cityList != null && cityList.size()>0) {
            for (TbCity city : cityList) {
                if (city == null || city.getIsActive() == Constants.IS_DELETE_TRUE) {
                    continue;
                }
                respCities.add(getCity(city.getId()));
            }
        }
        return PageObj.create(totalNum, pageNo, pageSize, respCities);
    }

    @Override
    public RespDistrict getDistrict(Integer districtId) {
        TbDistrict district = districtMapper.selectByPrimaryKey(districtId);
        if (district == null){
            return null;
        }
        RespDistrict respDistrict = new RespDistrict();
        respDistrict.setId(districtId);
        respDistrict.setCityId(district.getCityId());
        respDistrict.setName(district.getName());
        if (null != district.getPinyin()) {
            respDistrict.setInitial(district.getPinyin().substring(0,1));//首字母
        }
        respDistrict.setPinyin(district.getPinyin());
        respDistrict.setLat(district.getLat());
        respDistrict.setLng(district.getLng());
        return respDistrict;
    }

    @Override
    public PageObj<List<RespDistrict>> getDistrictList(Integer cityId, String keyWords, Integer pageNo, Integer pageSize) {
        TbDistrictExample example = new TbDistrictExample();
        TbDistrictExample.Criteria criteria = example.createCriteria();
        if (cityId != null && cityId != 0) {
            criteria.andCityIdEqualTo(cityId);
        }
        if (StringUtils.isNotEmpty(keyWords)) {
            criteria.andNameLike("%" + keyWords + "%");
        }
        int total = districtMapper.countByExample(example);
        example.setLimit(Limit.buildLimit(pageNo, pageSize));
        List<TbDistrict> districtList = districtMapper.selectByExample(example);
        List<RespDistrict> respDistricts = new ArrayList<>();
        if (districtList != null && districtList.size() > 0){
            for (TbDistrict tbDistrict : districtList){
                respDistricts.add(getDistrict(tbDistrict.getId()));
            }
        }
        return PageObj.create(total, pageNo, pageSize, respDistricts);
    }

    /**
     * 根据用户id获取用户信息
     * @param uid   用户ID
     * @return
     */
    @Override
    public RespUserInfoBase getUserInfoBase(Integer uid) {
        APIResponse<RespUserInfoBase> response = userServiceFacade.queryUserInfo(uid);
        if (response != null && response.isRet()){
            RespUserInfoBase uinfo = response.getData();
            return uinfo;
        }
        return null;
    }


    /**
     * 根据手机号获取用户信息
     * @param mobile
     * @return
     */
    public RespUserInfoBase getUserInfoByMobile(String mobile){
        APIResponse<RespUserInfoBase> response = userServiceFacade.queryUserInfoByPhone(mobile);
        if (response != null && response.isRet()){
            RespUserInfoBase uinfo = response.getData();
            return uinfo;
        }
        return null;
    }

    /**
     * 根据用户id和俱乐部id
     * 获取俱乐部成员信息
     * @param uid
     * @param clubId
     * @return
     */
    @Override
    public TbClubMember getClubMember(int uid, int clubId) {
        TbClubMemberExample example = new TbClubMemberExample();
        TbClubMemberExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(clubId);
        criteria.andUidEqualTo(uid);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> list = this.clubMemberMapper.selectByExample(example);
        return list.isEmpty()==true?null:list.get(0);
    }

    /**
     * 获取城市列表
     * @param provinceId
     * @return
     */
    @Override
    public List<TbCity> getCityList(int isLast,int provinceId) {
        TbCityExample example = new TbCityExample();
        TbCityExample.Criteria criteria = example.createCriteria();
        //is_enable 为1表示启用
        criteria.andIsEnableEqualTo(1);
        if(isLast == 0){
            example.setOrderByClause("id desc limit 0,1");
        }else{
            criteria.andProvinceIdEqualTo(provinceId);
            example.setOrderByClause("priority asc");
        }
        List<TbCity> cityList = this.cityMapper.selectByExample(example);
        return cityList;
    }

    /**
     * 获取地区列表
     * @param cityId
     * @return
     */
    @Override
    public List<TbDistrict> getDistrictList(int cityId) {
        TbDistrictExample example = new TbDistrictExample();
        TbDistrictExample.Criteria criteria = example.createCriteria();
        criteria.andCityIdEqualTo(cityId);
        example.setOrderByClause("priority asc");
        List<TbDistrict> list = this.districtMapper.selectByExample(example);
        return list;
    }

    /**
     * 获取俱乐部信息
     * @param clubId
     * @return
     */
    @Override
    public TbClub getClub(int clubId) {
        TbClub club = this.clubMapper.selectByPrimaryKey(clubId);
        return club;
    }

    @Override
    public TbClubType getClubType(Integer clubTypeId) {
        TbClubTypeExample example = new TbClubTypeExample();
        example.createCriteria().andCategoryIdEqualTo(clubTypeId);
        List<TbClubType> tbClubType = clubTypeMapper.selectByExample(example);
        if (tbClubType != null && tbClubType.size() > 0){
            return tbClubType.get(0);
        }
        return null;
    }

    /**
     * 获取俱乐部类型列表
     * @return
     */
    @Override
    public List<TbClubType> getClubTypeList() {
        TbClubTypeExample tbClubTypeExample = new TbClubTypeExample();
        tbClubTypeExample.setOrderByClause("priority asc");
        tbClubTypeExample.createCriteria().andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        return clubTypeMapper.selectByExample(tbClubTypeExample);
    }

    /**
     * 获取俱乐部属性
     * @param clubPropertyId
     * @return
     */
    @Override
    public TbClubProperty getClubProperty(Integer clubPropertyId) {
        return clubPropertyMapper.selectByPrimaryKey(clubPropertyId);
    }

    /**
     * 俱乐部属性列表
     * @param parentId
     * @param propertyLevel 属性级别：暂分为1，2两级
     * @return
     */
    @Override
    public List<TbClubProperty> getClubProperties(Integer parentId, Integer propertyLevel) {
        TbClubPropertyExample clubPropertyExample = new TbClubPropertyExample();
        TbClubPropertyExample.Criteria criteria = clubPropertyExample.createCriteria();
        if (parentId != null){
            criteria.andParentIdEqualTo(parentId);
        }
        if (propertyLevel != null){
            criteria.andPropertyLevelEqualTo(Byte.valueOf(String.valueOf(propertyLevel)));
        }
        return clubPropertyMapper.selectByExample(clubPropertyExample);
    }

    @Override
    public TbClubType getClubTypeByCategoryId(int categoryId){

        TbClubTypeExample example = new TbClubTypeExample();
        example.createCriteria()
                .andCategoryIdEqualTo(categoryId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubType> clubTypes = clubTypeMapper.selectByExample(example);
        if (clubTypes != null && clubTypes.size() > 0) {
            return clubTypes.get(0);
        }
        return null;
    }

    /**
     * 获取用户详细信息
     * @param uid
     * @return
     */
    @Override
    public RespUserInfoDetail getUserDetailInfo(int uid) {
        APIResponse<RespUserInfoDetail> response = userServiceFacade.queryUserInfoDetail(uid);
        if (response != null && response.isRet()){
            RespUserInfoDetail userDetail = response.getData();
            if(userDetail!=null)
                logger.info("用户详细信息：{}",userDetail.toString());
            return userDetail;
        }
        return null;
    }

    @Autowired
    private TbClubBindAccountMapper clubBindAccountMapper;
    @Autowired
    private TbClubWithdrawalsApplyMapper clubWithdrawalsApplyMapper;

    /**
     * 是否是实名认证俱乐部
     * @param clubId    俱乐部id
     * @return
     */
    @Override
    public boolean isRealNameAuthClub(int clubId) {

        TbClubBindAccountExample bindAccountExample = new TbClubBindAccountExample();
        bindAccountExample.createCriteria()
                .andClubIdEqualTo(clubId).andIsDeleteEqualTo(false);
        boolean isBindAccount = clubBindAccountMapper.countByExample(bindAccountExample)>0;

        TbClubWithdrawalsApplyExample withdrawalsApplyExample = new TbClubWithdrawalsApplyExample();
        withdrawalsApplyExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andWithdrawalsStatusEqualTo((byte)3)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        boolean isWithdrawSuccess = clubWithdrawalsApplyMapper.countByExample(withdrawalsApplyExample)>0;

        if (isBindAccount && isWithdrawSuccess){
            return true;
        }
        return false;
    }
}
